package com.gary.springcloud.controller;

import com.gary.springcloud.entity.CommonResult;
import com.gary.springcloud.entity.Payment;
import com.gary.springcloud.lb.LoadBlancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @author pengrui
 * @date 2020/12/30 - 17:19
 */
@RestController
public class OrderController {

    /**
     *  提供方 远程调用地址
     * 单机 public static final String PAYMENT_URL = "http://localhost:8001";
     * 集群 public static final String PAYMENT_URL = "http://CLOUD-PROVIDER-PAYMENT8001";
     */
    public static final String PAYMENT_URL = "http://CLOUD-PROVIDER-PAYMENT";

    /**
     *  注：org.springframework.cloud.client.discovery.DiscoveryClient
     */
    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private LoadBlancer loadBlancer;

    @Resource
    private RestTemplate restTemplate;

    @PostMapping("/consumer/payment/save")
    public CommonResult<Integer> save(@RequestBody Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL+"/payment/save/", payment, CommonResult.class);
    }

    @GetMapping("/consumer/payment/query/{id}")
    public CommonResult<Payment> queryById(@PathVariable("id") Long id) {
        // param1 请求地址， param2 请求参数， param3 返回类型
        return restTemplate.getForObject( PAYMENT_URL+"/payment/query/"+id, CommonResult.class);
    }

    @GetMapping("/consumer/payment/lb")
    public String getLB() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER-PAYMENT");
        ServiceInstance service = loadBlancer.getService(instances);
        URI uri = service.getUri();
        return restTemplate.getForObject(uri + "/payment/lb", String.class);
        //ResponseEntity<String> forEntity = restTemplate.getForEntity(uri + "/payment/lb", String.class);
        //if (forEntity == null ) {
        //    return "访问错误";
        //} else {
        //    String body = forEntity.getBody();
        //    return body;
        //}
    }
}
